$(function() {
    var rows_delete = 0;
    var mode = "add";
    var m_id = 0;
	var m_result=0;
    var url = 'controls/stock_model.php';
    var pid = 0;
    var cost=0;
	var code='';
	var approve_flage = $("#approve").val();
	var flag_admin = parseInt(approve_flage)==1?true:false;
	
	$(".approve_control").hide();
	$(".approved_control").hide();
	 
	$("#txtDateFrom_s,#txtDateTo_s").val(_cdate);
		
	var checkDate = $('.btndate1').datepicker().on('changeDate', function(ev) {
	  checkDate.hide();
	}).data('datepicker');
	
	var checkDate2 = $('.btndate2').datepicker().on('changeDate', function(ev) {
	  checkDate2.hide();
	}).data('datepicker');
    
	$("#txtAmount,#txtDiscount, #txtPrice").keypress(function(e) {

        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
	
	$("#btnAddProduct").live('click', function() {
            
        if (checkControl())
        {
            var typeName = $("#cboType option:selected").text();
            var discount = 0;
            if ($("#txtDiscount").val()!=""){
                discount=$("#txtDiscount").val();
            }
			var price=0;
			if (!(isNaN($("#txtPrice").val()))){
				price=$("#txtPrice").val();
			}
			var code;
			code = $("#cboProduct option:selected").attr('data-subtext');
			 
            //alert(typeName);
            $("#table_detail").dataTable().fnAddData([
                0, $("#cboProduct").val() ,code , typeName, $("#cboProduct option:selected").text(), $("#txtAmount").val(),price, discount , (parseInt( $("#txtAmount").val(),10) * price ) - discount
            ]);
			//$("#txtProduct").val("");
			$("#txtAmount,#txtPrice").val("0");
        }
    });
	
	$("#btnPrint").click(function(e){
		e.preventDefault(); 
		$("#frmPurchase").get(0).setAttribute('action', 'rpt_purchase.php');
		$("#pid").val(m_id);
		$(this).closest('form').attr('target', '_blank').submit().removeAttr('target');
	});
	
    $("#btnSave").live('click', function(e) {
		e.preventDefault();
        $("#txtPONo_,#txtPurchaseDate").jqBootstrapValidation({preventSubmit: false,
            submitSuccess: function($form, event) {
                event.preventDefault();
            }
        });
        //var cells = [];
        if (mode === "add") {
            var list = [];
            var rows = $('#table_detail').dataTable().fnGetNodes();
            var total_cost=0;
            var total_discount=0;
            for (var i = 0; i < rows.length; i++)
            {
                var row_data = $('#table_detail').dataTable().fnGetData(rows[i]);
                list.push({'pid': row_data[1],
                            'amt': row_data[5],
                            'cost':row_data[6],
                            'discount':row_data[7]
                        });
                total_cost += parseFloat(row_data[8]);
                total_discount += parseFloat(row_data[7]);
            }

            var amt_total = rows.length;

            if (amt_total === 0) {
                $("#Error").css('display', '');
                return;
            } else {
                $("#Error").css('display', 'none');
            }
			 
			var supplier=$("#cbosupplier").val();
            var date = $("#txtPurchaseDate").val();
            var no =  $("#txtPONo_").val();
            var remark = $("#txtRemark").val();
           

            $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: {"m": "add_purchase", "no": no,  "amt": amt_total, "supplier":supplier, "list": list, "remark": remark,"discount":total_discount,"total":total_cost},
                success: function(data) {
                    //var obj = eval('(' + data + ')');
					$("#btnSearch").click();
					//LoadData('','',0, $("#txtDateFrom_s").val(), $("#txtDateTo_s").val(),'');
					$("#popup").modal('hide');
                     
                }
            });

        } else {

        }

        $("#txtPONo_,#txtPurchaseDate").jqBootstrapValidation("destroy");
    });
  
	$("#btnApp").click(function(){
		m_result=3;
		$.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "upStatusPO", "id": m_id,"status":m_result },
            success: function(data) {
				$("#btnSearch").click();
				//LoadData('','',0, $("#txtDateFrom_s").val(), $("#txtDateTo_s").val(),'');
			   $("#popup").modal('hide');
				
            }
        });
	});
	
	$("#btnNotApp").click(function(){
	 
		m_result=4;
		$.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "upStatusPO", "id": m_id,"status":m_result },
            success: function(data) {
				 $("#btnSearch").click();
				 
				//LoadData('','',0, $("#txtDateFrom_s").val(), $("#txtDateTo_s").val(),'');
			   $("#popup").modal('hide');
				
            }
        });
	});
  
	$(".btnApprove").live('click', function() {
		 mode = "approve";
		$("#btnCancel").html('ปิด');
		$("#cbosupplier").attr('disabled','disabled');
		$("#txtRemark").attr('disabled','disabled');
		$(".hidden_control").hide();
        var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
        var data = $('#resultData').dataTable().fnGetData(rows);
		
		 m_id = data[1];
		  
		 if (data[11] == 4 || data[11] ==3){
			 $(".approve_control").hide();
			 $(".approved_control").show();
			 
		 }else{
			 $(".approve_control").show();
			 $(".approved_control").hide();
		 }
		 
		   SetTableDetail(m_id);
		   $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getPurchaseDetail", "id": m_id},
            success: function(data) {
                //alert(data);
                var obj = eval('(' + data + ')');
                $("#txtPONo_").val(obj['po_no']);
                $("#txtPurchaseDate").val(obj['purchasedate']);
                $("#txtRemark").val(obj['remark']);
				$("#cbosupplier").val(obj['supplier']);
            }
        }); 
	});
	
	$(".btnEdit").live('click', function() {
        $("#btnCancel").html('ปิด');
		$("#cbosupplier").attr('disabled','disabled');
		$("#txtRemark").attr('disabled','disabled');
        mode = "edit";
        $(".hidden_control").hide();
        var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
        var data = $('#resultData').dataTable().fnGetData(rows);
		
        m_id = data[1];
		  
		 if (data[11] == 4 || data[11] ==3){
			 $(".approved_control").show();
			 
		 }else{
			 $(".approved_control").hide();
		 }
		 
		 
        SetTableDetail(m_id);

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getPurchaseDetail", "id": m_id},
            success: function(data) {
                //alert(data);
                var obj = eval('(' + data + ')');
                $("#txtPONo_").val(obj['po_no']);
                $("#txtPurchaseDate").val(obj['purchasedate']);
                $("#txtRemark").val(obj['remark']);
				$("#cbosupplier").val(obj['supplier']);
            }
        });
    });
    $("#btnAdd").live('click', function() {
	
        $("#btnCancel").html('ยกเลิก');
		$(".approved_control").hide();
        $("#Error").css('display', 'none');
		$("#cbosupplier").removeAttr('disabled');
		$("#txtRemark").removeAttr('disabled');
        $("#txtRemark").val('');
        mode = "add";
        $(".hidden_control").show();
        var now = new Date();
        var today = ("0" + now.getDate()).slice(-2) + '/' + ("0" + (now.getMonth() + 1)).slice(-2) + '/' + now.getFullYear();
        $("#txtPurchaseDate").val(today);
        /*$.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getRuning", "t": "PO"},
            success: function(data) {
                $("#txtPONo_").val(data);
            }
        });*/
        //First Time 
        SetTableDetail(0);

    });
    $(".btnDel_detail").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#table_detail').dataTable().fnGetPosition(rows);
        $('#table_detail').dataTable().fnDeleteRow(rows_delete);
        $('#table_detail').dataTable().fnDraw();
    });
    $("#btnSearch").click(function() {
        var _rq = "";//$("#txtRequestNo_S").val();
        var _no = $("#txtPurchaseNo_S").val();
        var _s = $("#cboPurchase").val();
        var _df = $("#txtDateFrom_s").val();
        var _dt = $("#txtDateTo_s").val();
		var _supplier=$("#cbosupplier_s").val();
        var _emp = "";
        if ($('#txtEmployee').length)
            _emp = $("#txtEmployee").val();
				
        LoadData(_rq,_no, _s, _df, _dt, _emp, _supplier);
    });
	
	$("#cbosupplier_s").append($('<option></option>').val(0).html(' '));
	$.get(url,{"m":"supplier"},function(data){
		var obj = eval('(' + data + ')');
        if (obj !== null) {
            $.each(obj, function(index, text) {
                $("#cbosupplier,#cbosupplier_s").append(
                        $('<option></option>').val(text).html(index));
            });
		//	$("#cbosupplier").selectpicker({size:5});
        }
		
	});
    $.get(url, {"m": "purchase"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj !== null) {
            $.each(obj, function(index, text) {
                $("#cboPurchase").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
        }
    });

	
	function checkControl() {
			var bln = true;
			// if ($("#txtProduct").val() == "" || pid == "" || pid == 0) {
				// $("#txtProduct").attr('style', "background-color:#fddedb;border:1px solid #f99891");
				// bln = bln && false;
			// } else {
				// $("#txtProduct").removeAttr('style');
				// bln = bln && true;
			// }
			if ($("#txtPrice").val() == "") {
				$("#txtPrice").attr('style', "background-color:#fddedb;border:1px solid #f99891");
				bln = bln && true;
			} else {
				$("#txtPrice").removeAttr('style');
				bln = bln && true;
			}
			if ($("#txtAmount").val() == "") {
				$("#txtAmount").attr('style', "background-color:#fddedb;border:1px solid #f99891");
				bln = bln && true;
			} else {
				$("#txtAmount").removeAttr('style');
				bln = bln && true;
			}
			return bln; 
	   }
	
    $.get(url, {"m": "pdtype"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#cboType").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
        }
    });
	
/*	$.get(url, {"m": "employee"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#cboEmployee").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
			$(".select_emp").selectpicker(
				{
					size:5
					 
				}
			);
        }
    });*/
	
    //Main Table
    function LoadData(rq,no, status, df, dt, name, supplier) {
        $("#resultData tbody tr").remove();


        $('#resultData').dataTable({
            "bProcessing": true,
            "bFilter": false,
			"bAutoWidth": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_po"},
                {"name": "rq","value":rq},
                {"name": "no", "value": no},
                {"name": "status", "value": status},
                {"name": "datefrom", "value": df},
                {"name": "dateto", "value": dt},
                {"name": "name", "value": name} ,
				{"name": "supplier", "value": supplier},
				{"name": "app_flage", "value":approve_flage}
                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
                {"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "center"},
                {"bSortable": true, "aTargets": [4], "sClass": "center"},
                {"bVisible": flag_admin, "aTargets": [5], "sClass": "center"},
				{"bSortable": true, "aTargets": [6], "sClass": "center"},
                {"bSortable": true, "aTargets": [7], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [8], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [9], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [10], "sClass": "center",
                    "mRender": function(data, type, full) {
                        var tmp = "";
                        if (full[11] == 3)
                            tmp = "<span class='label label-success'>" + data + "</span>";
                        else if (full[11] == 4)
                            tmp = "<span class='label label-important'>" + data + "</span>";
                        else
                            tmp = data;
                        return tmp;
                    }

                },
                {"bVisible": false, "aTargets": [11]},
                {"aTargets": [12],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
					if (flag_admin)
							return "<a href='#popup' data-toggle='modal'><img src='img/check_product.png' class='btnApprove' style='cursor:pointer;'/></a>";
						else
							return "<a href='#popup' data-toggle='modal'><img src='img/List.png' class='btnEdit' style='cursor:pointer;'/></a>";
							
                        
                    }
                },
                {"aTargets": [13],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						if (!flag_admin){
							if (full[11] == 4)
								return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
							else
								return "";
						}else{
							return "";
						}
                    }
                }

            ]
            , "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }
        });

    }


    $("#btnDelete").live('click', function() {

        var row_id = $('#resultData').dataTable().fnGetData(rows_delete);

        var id = row_id[1];

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "del", "id": id},
            success: function(data) {
                $("#popupConfirm").modal('hide');

                $('#resultData').dataTable().fnDeleteRow(rows_delete);
                $('#resultData').dataTable().fnDraw();
            }
        });

    });

    $(".btnDel").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

    });

	//Initial load
	$.post(url, {"m": "getProductwithDetail", "t": 1}, function(data) {
			
			var obj = eval('(' + data + ')');
			if (obj != null) {
				$("#cboProduct").find('option').remove();	
				$.each(obj, function(index, text) {
					$("#cboProduct").append(
							$('<option data-subtext="'+text['code']+'"></option>').val(index).html(text['name'])
					);
				});
				$(".select_product").selectpicker('refresh');
			 
			}
		});
	
    $("#cboType").live('change', function() {
		var ctype = $("#cboType option:selected").val();
		$.post(url, {"m": "getProductwithDetail", "t": ctype}, function(data) {
			
			var obj = eval('(' + data + ')');
			if (obj != null) {
				$("#cboProduct").find('option').remove();	
				$.each(obj, function(index, text) {
					$("#cboProduct").append(
							$('<option data-subtext="'+text['code']+'"></option>').val(index).html(text['name'])
					);
				});
				$(".select_product").selectpicker('refresh');
			 
			}
		});
		// TODO : JOE Comment
      //  LoadProductToTextBox(ctype);
    });
    function LoadProductToTextBox(t) {
        //Clear data
        $('#txtProduct').off();
        $('#txtProduct').data('typeahead', (data = null));

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getProductwithDetail", "t": t},
            success: function(data) {
               // var sourceArr = [];
                var jsonObj = $.parseJSON(data);

                $('#txtProduct').typeahead({
                    source: function(query, process) {
                        objects = [];
                        map = {};
                        var data = jsonObj; // Or get your JSON dynamically and load it into this variable
                        $.each(data, function(i, object) {
                            map[object.label] = object;
                            objects.push(object.label);
                        });
                        process(objects);
                    },
                    updater: function(item) {
                        // $('hiddenInputElement').val(map[item].id);
                        pid = map[item].id;
                        cost = map[item].cost;
						code = map[item].code;
                        return item;
                    }
                });
            }
        });
    }
    //initial get product 
    if ($("#txtProduct")[0]) {
        LoadProductToTextBox(1);
    }
    ;
    function SetTableDetail(id) {
        $("#table_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "prd_detail"},
                {"name": "id", "value": id},
                 {"name": "type", "value": "PO"}
                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
				{"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "center"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [5], "sClass": "center"},
                {"bSortable": true, "aTargets": [6], "sClass": "center"},
                {"bSortable": true, "aTargets": [7], "sClass": "center"},
                {"bSortable": true, "aTargets": [8], "sClass": "center"},
                {"aTargets": [9],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                        if (mode == "add")
                            return "<a href='#'  ><img src='img/delete-file.png' class='btnDel_detail' style='cursor:pointer;'/></a>";
                        else
                            return "";
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }

	 $("#btnSearch").click();
});
 
 

